<?php
require_once $ubi['SERVER']['SERVER_ROOT'] . "/controller/ctlAbstract.php";
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busUser.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/generalFunctions.php';

class ChangeController extends AbstractController {
	private $_userBus;
	
	public function __construct(){
		$this->_userBus = new UserBus();
	}
	
	public function main(array $getVars)
	{
		if ($getVars['type'] == 'password')
		{
			$token = $getVars['token'];
			
			if ($token)
			{
				if (isset($_POST['txtPassword']))
				{
					if ($_POST['txtPassword'] == $_POST['txtRetypePassword'])
					{
						$user = $this->_userBus->getUserByToken($token);

						if ($user)
						{
							$user->setPasswordHash(md5($_POST['txtPassword']));
							$result = $this->_userBus->updatePassword($user);

							if ($result)
							{
								$notice = 'ChangePasswordSuccessfully';
								require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewNotice.php';
								
								//create a token
								$token = GeneralFunctions::createToken();
					
								//change token of the user
								$user->setToken($token);
					
								//update token
								$result = $this->_userBus->updateToken($user);
							}
						}
						else 
						{
							$notice = 'TokenDoesNotExist';
							require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewNotice.php';
						}
					}
					else 
					{
						$notice = 'PasswordAndRetypePasswordMismatch';
						require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewNotice.php';
					}
				}
				else 
				{
					$user = $this->_userBus->getUserByToken($token);
					if ($user)
					{
						require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewChangePasswordWithToken.php';
					}
					else 
					{
						$notice = 'TokenDoesNotExist';
						require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewNotice.php';
					}
				}
			}
			else 
			{
			}
		}
		else 
		{
			$notice = 'PageNotFound';
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewNotice.php';
		}
	}
}